home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 9703 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.8 KB  |  52 lines

  1. Path: doc.ic.ac.uk!not-for-mail
  2. From: njs3@doc.ic.ac.uk (Niall Smart)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: revised code of calling a function twice from printf
  5. Date: 12 Mar 1996 21:28:17 -0000
  6. Organization: Dept. of Computing, Imperial College, University of London, UK.
  7. Distribution: world
  8. Message-ID: <4i4q9h$7pi@oak62.doc.ic.ac.uk>
  9. References: <4hfs54$k4e@newsbf02.news.aol.com> <Pine.A32.3.91.960304174215.96209J-100000@black.weeg.uiowa.edu>
  10. Reply-To: njs3@doc.ic.ac.uk (Niall Smart)
  11. NNTP-Posting-Host: oak62.doc.ic.ac.uk
  12. X-Newsreader: mxrn 6.18-23
  13.  
  14.  
  15. In article <Pine.A32.3.91.960304174215.96209J-100000@black.weeg.uiowa.edu>, The Amorphous Mass <robinson@blue.weeg.uiowa.edu> writes:
  16.  
  17. |>> Here is the actual code , modified with everyone's suggestions.  However
  18. |>> there is still a bug in here somewhere.  Can anyone please explain what is
  19. |>> wrong with this.
  20. |>
  21. |>  You're returning a pointer to an automatic variable, which is 
  22. |>guaranteed bad news.
  23.  
  24. |>> char *display_drug_type(int drug_index) {
  25. |>>    char drug_type[81]="\0";
  26. |>
  27. |>  make this
  28. |>     static char drug_type[81];  /* static variables are automatically
  29. |>                  initialized to 0, and it's safe to
  30. |>                  return their addresses -- they "persist" */
  31. |>
  32.  
  33. I beg to differ, this approach is definately *not* safe - subsequent calls
  34. to display_drug_type will overwrite the memory (drug_type[]) that may be
  35. referenced by other pointers as shown in this example.
  36.  
  37.     char *pA;
  38.     char *pB;
  39.  
  40.     pA = display_drug_type(iSomeInt);
  41.     pB = display_drug_type(iSomeOtherInt);
  42.  
  43. now both *pa and *pB are the same, even if iSomeInt != iSomeOtherInt. This
  44. is because the area of memory that display_drug_type returns is always the
  45. same. A better solution is to take a char * as an argument or malloc() the
  46. return.
  47.  
  48. Niall Smart
  49. Imperial College London
  50. njs3@doc.ic.ac.uk
  51.  
  52.